package com.fingard.dsp.bank.directbank.bfb01;

import com.bfb.cap.sdk.SecureUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 邦付宝历史明细
 * <p>
 * 备注：在历史明细接口中调用邦付宝批量收付对账单接口，从而实现邦付宝对账单以银行明细形式返回
 *
 * @author cruise
 */
public class BFB01Transaction extends BFB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req7516.actNum, "*");
            if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
                if (actItem == null) {
                    throw new Exception("未找到账号" + p_req7516.actNum + "商户配置信息,请检查config.xml相关配置!");
                } else {
                    throw new Exception("账号" + p_req7516.actNum + "商户证书文件不存在,请检查config.xml相关配置!");
                }
            }

            HashMap<String, String> signMap = new HashMap<String, String>();

            signMap.put("version", "1.0");
            signMap.put("transCode", "settlement");
            signMap.put("signType", "01");
            signMap.put("merchantId", actItem.merchantId);
            signMap.put("txnDate", Format.Date8Format.format(p_req7516.getDateFrom()));
            signMap.put("checkType", "01"); /* 00: 单笔    01:全部(批量和单笔)*/

            String[] tmpStrRet = sendToBank(signMap, actItem);

            if (tmpStrRet[0].length() == 0) {
                Map<String, String> respMap = getRet(tmpStrRet[1]);
                if (respMap.size() > 0) {
                    String backCode = respMap.get("respCode");
                    if ("B0".equals(backCode)) {
                        // 获取对账文件密文
                        String fileContent = respMap.get("fileContent");

                        // 解密文件内容
                        byte[] backStatementBytes = SecureUtil.inflater(SecureUtil.base64Decode(fileContent.getBytes(getCharset())));
                        String tmpRetStr = new String(backStatementBytes, getCharset());

                        WriteBankLogStep3(tmpRetStr);

                        String billArray[] = tmpRetStr.split("\n");
                        for (String singelBill : billArray) {
                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();

                            tmpRetDetail.actNum = p_req7516.actNum;
                            tmpRetDetail.actArea = p_req7516.actArea;
                            tmpRetDetail.cur = p_req7516.actCur;

                            String busType = singelBill.substring(65, 69).trim();
                            if ("02".equals(busType)) {
                                tmpRetDetail.cdFlag = "2";// 收款
                                tmpRetDetail.busType = "代收";
                            } else {
                                tmpRetDetail.cdFlag = "1";// 付款
                                tmpRetDetail.busType = "代付";
                            }

                            tmpRetDetail.reqBatchNO = singelBill.substring(79, 83).trim();
//							tmpRetDetail.askNumber = singelBill.substring(84, 148).trim();
                            tmpRetDetail.comment = singelBill.substring(84, 148).trim();

                            String busDate = singelBill.substring(149, 157).trim();
                            Date busDateObj = Format.Date8Format.parse(busDate);

                            tmpRetDetail.tranDate = Format.Date10Format.format(busDateObj);
                            tmpRetDetail.tranTime = Format.DateTimeFormat.format(busDateObj);
                            tmpRetDetail.postTimestamp = Format.DateTime14Format.format(busDateObj);
                            tmpRetDetail.valueDate = Format.Date10Format.format(busDateObj);

                            tmpRetDetail.tranAmt = StringHelper.amountDivide100(convertMoney(singelBill.substring(158, 176).trim()));

                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = respMap.get("respMsg");
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = "返回数据格式错误!";
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            WriteBankLogLn(e);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        retAts.writeStart();

        retAts.writeRespCode("0");
        retAts.writeRespInfo("不支持的交易类型:" + p_req7515.reqHeader.transType);

        retAts.writeEnd();
        return retAts;
    }
}
